<template>
    <Popup ref="popupRef" :title="title" :form-data="formData" :rules="rules" :width="500" :height="500" @submit="handleSubmit" @cancel="handleCancel"  >
        <a-form-item field="name" label="职位名称">
            <a-input v-model="formData.name" placeholder="请输入职位名称" />
        </a-form-item>
        <a-form-item field="department_id" label="部门">
            <a-select v-model="formData.department_id" :options="options" clearable placeholder="请选择部门" />
        </a-form-item>
    </Popup>
</template>

<script setup lang="ts">
import { addPosition, updatePosition } from '@/api/system/organize/position'
import { getDepartmentLists } from '@/api/system/organize/department'
import Popup from '@/components/Popup/index.vue'
const popupRef = ref<InstanceType<typeof Popup>>()
const emits = defineEmits<{
    (e: 'success'): void
}>()

interface FormData {
    id?: number | null
    name: string
    department_id: string
}
const formData = reactive<FormData>({
    id: null,
    name: '',
    department_id: ''
})

const rules = reactive({
    name: [{ required: true, message: '请输入职位名称' }]
})


const mode = ref<'add' | 'edit'>('add')

const title = computed(() => {
    return mode.value === 'add' ? '新增职位' : '编辑职位'
})


const open = (type: 'add' | 'edit') => {
    mode.value = type
    popupRef.value?.open()
    nextTick(() => {
        getDepartmentList()
    })
}


const options = ref<any[]>([])
const getDepartmentList = async () => {
    const res = await getDepartmentLists()
    options.value = res.map((item: any) => ({
        label: item.name,
        value: item.id
    }))
}

const setFormData = async (record: Record<any, any>) => {
    if (record) {
        // 使用解构赋值来合并数据

        for (const key in formData) {
            if (record[key] != null && record[key] != undefined) {
                //@ts-ignore
                formData[key] = record[key]
            }
        }
        // Object.assign(formData, rest)
        // 确保弹窗组件也更新了数据
        nextTick(() => {
            popupRef.value?.setFormData(formData)
        })
    }

}

const handleSubmit = async () => {
    try {
        mode.value === 'add' ? await addPosition(formData) : await updatePosition(formData)
        popupRef.value?.close()
        popupRef.value?.closeLoading()
        emits('success')
    } catch (error) {
        popupRef.value?.closeLoading()
    }
}


const handleCancel = () => {
    popupRef.value?.close()
}
defineExpose({
    open,
    setFormData
})


</script>
